package com.huike.web.controller.common;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.huike.clues.mapper.SystemDictDataMapper;
import com.huike.common.config.HuiKeConfig;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.domain.UploadFileAjaxResult;
import com.huike.common.core.domain.entity.SysDictTypeDTO;
import com.huike.common.result.FileDownloadAjaxResult;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.file.AliOssUtil;
import com.huike.common.utils.file.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Description 通用请求处理
 * @Date 2023-10-10
 */
@RestController
@RequestMapping("/common")
@Slf4j
@AllArgsConstructor
@Api("通用相关接口")
public class CommonController {

    private AliOssUtil aliOssUtil;

    private SystemDictDataMapper systemDictDataMapper;

    @PostMapping("/upload")
    @ApiOperation("合同上传")
    public UploadFileAjaxResult contractUpload(MultipartFile file) {
        log.info("上传文件名：{}", file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            UploadFileAjaxResult uploadFileAjaxResult = new UploadFileAjaxResult();
            uploadFileAjaxResult.setFileName(objectName);
            uploadFileAjaxResult.setUrl(filePath);
            uploadFileAjaxResult.setCode(200);
            uploadFileAjaxResult.setMsg("操作成功");
            return uploadFileAjaxResult;
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return UploadFileAjaxResult.error();
    }

//    /**
//     * 通用下载接口 未测试！！！
//     * @param fileName
//     * @param delete
//     * @param response
//     */
//    @GetMapping("/download")
//    @ApiOperation("下载")
//    public void contractDownload(@RequestParam String fileName, @RequestParam Boolean delete, HttpServletResponse response) {
//        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/sys_dict_type.xlsx");
//             OutputStream outputStream = response.getOutputStream();
//             ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build()
//        ) {
//            response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // 设置文件名
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 设置文件类型
//
//            WriteSheet writeSheet = EasyExcel.writerSheet().build();
//            List<SysDictTypeDTO> list = systemDictDataMapper.selectAll();
//            excelWriter.fill(list, writeSheet);
//
//            excelWriter.finish();
//            outputStream.flush();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 通用下载接口 未测试！！！
     * @param fileName
     * @param delete
     * @param response
     */
    @GetMapping("/download")
    @ApiOperation("下载")
    public void download(String fileName, Boolean delete, HttpServletResponse response)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            //下载路径
            String downloadPath = HuiKeConfig.getDownloadPath() + fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
